<div class="main">
  <a path="/home">home</a>
  <a path="/detail">detail</a>
  <div id="content"><span>暂无内容</span></div>
</div>

<script>
const routers = [{
  path: '/home',
  component: `<span>我是Home页面</span>`
}, {
  path: '/detail',
  component: `<span>我是Detail页面</span>`
}, {
  path: '/',
  component: '<span>暂无内容</span>'
}]

function Router(routers) {
  this.routersAction = {}
  // 初始化生成 routers
  routers.forEach((router) => {
    this.routersAction[router.path] = () => {
      document.getElementById("content").innerHTML = router.component;
    }
  })
  const links = [...document.getElementsByTagName('a')]
  links.forEach(link => {
    // 通过a标签的点击事件，触发updateView  
    link.addEventListener('click', (e) => {
      e.preventDefault();
      window.history.pushState({}, null, link.getAttribute('path'))
      this.updateView()
    })
  })
  this.updateView = function() {
    let url = window.location.pathname || '/'
    console.log(url, '匹配的url地址')
    this.routersAction[url] && this.routersAction[url]()
  }
  // 路由加载触发视图更新
  window.addEventListener('load', this.updateView.bind(this))
  // 路由改变触发视图更新
  window.addEventListener('popstate', this.updateView.bind(this))
}
// 实例化 history 模式的 Router
const router = new Router(routers)
</script>
